

import 'package:flutter/material.dart';
import 'package:flutter_trip/widget/loading_container.dart';
import 'package:flutter_trip/widget/loading_container.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';

import '../dao/travel_dao.dart';
import '../model/travel_model.dart';
import '../widget/fwebview.dart';

const TRAVEL_URL =
    'https://m.ctrip.com/restapi/soa2/16189/json/searchTripShootListForHomePageV2?_fxpcqlniredt=09031014111431397988&__gw_appid=99999999&__gw_ver=1.0&__gw_from=10650013707&__gw_platform=H5';
const PAGE_SIZE = 10;
class TravelChildPage extends StatefulWidget {
  final String? url;
  final Map params;
  final String groupChannelCode;

  const TravelChildPage({super.key, this.url,required this.params,required this.groupChannelCode});

  @override
  State<TravelChildPage> createState() => _TravelChildPageState();
}

class _TravelChildPageState extends State<TravelChildPage> with AutomaticKeepAliveClientMixin{
  bool _isLoading = true;
  int pageIndex = 1;
  TravelItemModel? travelItemModel;
  List<TravelItem>? resultList = [];
  ScrollController _scrollController = ScrollController();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _loadData();
    _scrollController.addListener(() {
      if(_scrollController.position.pixels == _scrollController.position.maxScrollExtent){
        _loadMore();
      }
    });
  }
  @override
  void dispose() {
    // TODO: implement dispose
    _scrollController.dispose();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: LoadingContainer(
        child: RefreshIndicator(
          onRefresh: _onRefresh,
          child: MediaQuery.removePadding(context: context, child: _gridView(),removeTop: true,),
        ),
        isLoading: _isLoading,
      ),
    );
  }

  _loadMore(){
    pageIndex ++;
    _loadData();
  }

  Future<Null> _onRefresh() async{
    pageIndex = 1;
    _loadData();
    return null;
  }

  _loadData(){
    TravelDao.fetch(widget.url ?? TRAVEL_URL, widget.params , widget.groupChannelCode, pageIndex,PAGE_SIZE).then((value){
      setState(() {
        travelItemModel = value;
        if (pageIndex > 1){
          resultList?.addAll(value?.resultList ?? []);
        }else{
          resultList = value.resultList;
        }

      });
      _isLoading = false;
    }).catchError((e){
      print(e);
      _isLoading = false;
    });


  }

  _gridView(){
     return MasonryGridView.count(
       controller: _scrollController,
         crossAxisCount: 2,
         itemCount: resultList?.length ?? 0,
         itemBuilder: (BuildContext context, int index) {
           return GestureDetector(
             onTap: (){
               String url = resultList?[index]?.article?.urls?[0]?.h5Url ?? "";
               if(url.length > 0){
                 Navigator.push(context,MaterialPageRoute(builder: (context) => FWebView(url: url,title: '详情',)));
               }

             },
             child: Card(
               child: PhysicalModel(
                 color: Colors.transparent,
                 clipBehavior: Clip.antiAlias,
                 borderRadius: BorderRadius.circular(5),
                 child: Column(
                   crossAxisAlignment: CrossAxisAlignment.start,
                   children: [
                     _itemImage(context,resultList![index]),
                     _content(resultList![index]),
                     _infoText(resultList![index]),
                   ],
                 ),
               ),
             )
           );
         }
         );
  }

  _itemImage(BuildContext context,TravelItem travelItem){
    return Stack(
      children: [
        Image.network(travelItem.article.images[0].dynamicUrl),
        Positioned(
          left: 8,
            bottom: 8,
            child: Container(
              padding: EdgeInsets.fromLTRB(5, 1, 5, 1),
              decoration: BoxDecoration(
                color: Colors.black54,
                borderRadius: BorderRadius.circular(10),
              ),
              child: Row(
                children: [
                  Icon(Icons.location_on,color: Colors.white,size: 12,),
                  LimitedBox(
                    maxWidth: 130,
                    child:  Text(_poiName(travelItem),style: TextStyle(fontSize: 12,color: Colors.white),maxLines: 1,overflow: TextOverflow.ellipsis,),
                  ),
                ],
              ),
            )
        )
        
      ],
    );
  }

  String _poiName(TravelItem travelItem){
    if (travelItem.article.pois == null || travelItem.article.pois?.length == 0){
      return '未知';
    }else{
      return travelItem.article.pois?[0]?.poiName ?? "";
    }
  }

  _content(TravelItem travelItem){
    return Container(
      padding: EdgeInsets.all(4),
      child: Text(travelItem.article.articleTitle,style: TextStyle(fontSize: 14,color: Colors.black87),maxLines: 2,overflow: TextOverflow.ellipsis,),
    );
  }

  _infoText(TravelItem travelItem){
    return Container(
      padding: EdgeInsets.fromLTRB(5, 0, 5, 5),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            children: [
              PhysicalModel(
                  color: Colors.transparent,
                  clipBehavior: Clip.antiAlias,
                borderRadius: BorderRadius.circular(12),
                child: Image.network(travelItem.article.author?.coverImage?.dynamicUrl ?? "",width: 24,height: 24,),
              ),
              Container(
                padding: EdgeInsets.only(left: 5),
                child: Text(travelItem.article.author?.nickName ?? "",style: TextStyle(fontSize: 12,color: Colors.black87),maxLines: 1,overflow: TextOverflow.ellipsis,),
              )
            ],
          ),
          Row(
           children: [
             Icon(Icons.thumb_up,size: 14,color: Colors.grey,),
             Container(
               padding: EdgeInsets.only(left: 3),
               child: Text('${travelItem.article.likeCount}',style: TextStyle(fontSize: 10,color: Colors.black87),maxLines: 1,overflow: TextOverflow.ellipsis,),
             )
           ],
          ),
        ],
      ),
    );

  }

  @override
  bool get wantKeepAlive => true;


}
